package com.monad.firemoth.config.satoken.interceptor;

import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.monad.firemoth.common.utils.Result;
import com.monad.firemoth.system.entity.Menu;
import com.monad.firemoth.system.entity.MenuRole;
import com.monad.firemoth.system.entity.Role;
import com.monad.firemoth.system.service.MenuRoleService;
import com.monad.firemoth.system.service.MenuService;
import com.monad.firemoth.system.service.RoleService;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.servlet.HandlerInterceptor;

import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;

/**
 * @author 单C胞生物
 * @version 1.0.0
 * @date 2024/4/21 16:22
 * @description 权限拦截器
 */
@Component
public class AuthInterceptor implements HandlerInterceptor {

    @Autowired
    private RoleService roleService;
    @Autowired
    private MenuService menuService;
    @Autowired
    private MenuRoleService menuRoleService;

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        List<Role> roles = roleService.getRoleByUserId(StpUtil.getLoginIdAsLong());
        // 超级管理员全部放行
        for (Role role : roles) {
            if (role.getRoleId().equals(1L) && role.getRoleTag().equals("admin")) {
                return true;
            }
        }
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        String requestURI = request.getRequestURI();
        for (Menu menu : menuService.list()) {
            // 查找 与请求路径匹配的菜单数据
            if (!StringUtils.isEmpty(menu.getPath()) && antPathMatcher.match(contextPath + menu.getPath(), requestURI)) {
                // 判断是否有权限
                for (Role role : roles) {
                    MenuRole menuRole = menuRoleService.getOne(Wrappers.lambdaQuery(MenuRole.class).eq(MenuRole::getRoleId, role.getRoleId()).eq(MenuRole::getMenuId, menu.getMenuId()));
                    if (!Objects.isNull(menuRole)) {
                        return true;
                    }
                }
                response.setCharacterEncoding("utf-8");
                response.setContentType("application/json");
                PrintWriter writer = response.getWriter();
                Result error = Result.error(403, "无[" + menu.getMenuName() + "]权限，请联系管理员！");
                writer.write(new ObjectMapper().writeValueAsString(error));
                writer.flush();
                writer.close();
                return false;
            }
        }
        return true;
    }
}
